<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>区域管理</title>
    <link rel="stylesheet" href="${ctxPath}/assets/libs/layui/css/layui.css"/>
    <link rel="stylesheet" href="${ctxPath}/assets/module/admin.css"/>
</head>
<body>
<% include("layout/loading.html"){} %>

<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form toolbar">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label w-auto">搜索：</label>
                        <div class="layui-input-inline mr0">
                            <input id="edtSearch" class="layui-input" type="text" placeholder="请输入关键字"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button id="btnSearch" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
                        <button id="btnAdd" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>
                    </div>
                </div>
            </div>

            <table class="layui-table" id="areaTable" lay-filter="areaTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!-- 表单弹窗 -->
<script type="text/html" id="modelArea">
    <form id="modelAreaForm" lay-filter="modelAreaForm" class="layui-form model-form">
        <input id="name" name="name" type="hidden"/>
        <div class="layui-form-item" id="type">
            <label class="layui-form-label">区域类型</label>
            <div class="layui-input-block">
                <input name="type" type="radio" value="2" title="城市" checked lay-filter="type"/>
                <input name="type" type="radio" value="3" title="地区" lay-filter="type"/>
            </div>
        </div>
        <div class="layui-form-item" hidden id="city">
            <label class="layui-form-label">城市</label>
            <div class="layui-input-block">
                <select id="parentId" name="parentId"  lay-filter="parentId"  lay-search="parentId" >
                    <option value="" >请选择上级城市</option>
                    <% for(city in cities) { %>
                        <option value="${city.id}">${city.name}</option>
                    <% } %>
                </select>
            </div>
        </div>
        <div class="layui-form-item" id="area">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-block">
                <select id="id" name="id" xm-select="id" lay-filter="id"  lay-verType="tips" lay-verify="required" lay-search="" required>
                    <option value="" >请选择</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input name="sortNum" placeholder="请输入排序" type="number" class="layui-input" min="0" max="100" lay-verType="tips" lay-verify="required|number" required/>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closePageDialog">取消</button>
            <button class="layui-btn" lay-filter="modelAreaSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script type="text/javascript" src="${ctxPath}/assets/libs/layui/layui.js"></script>
<script type="text/javascript" src="${ctxPath}/assets/js/common.js"></script>
<script>
    layui.use(['layer', 'form', 'table', 'util', 'admin', 'treetable'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var util = layui.util;
        var admin = layui.admin;
        var treetable = layui.treetable;
        window.treetable = treetable;
     
        // 渲染表格
        function renderTable(where) {
            treetable.render({
                treeColIndex: 2,
                treeSpid: -1,
                treeIdName: 'id',
                treePidName: 'parentId',
                elem: '#areaTable',
                url: 'list',
                where: where,
                page: false,
                cellMinWidth: 100,
                cols: [[
                    {type: 'numbers'},
                    {field: 'id', title: 'ID', hide: true},
                    {field: 'name', title: '名称'},
                    {field: 'type', title: '类型',templet:function(d){return ",省,市,区".split(",")[d.type]}},
                    {field: 'sortNum', title: '排序'},
                    {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 200}
                ]]
            });
        }
        renderTable();
        //轮子:前端区域字典
        window.$ = $;
        window.jQuery = $;
        var cities = ${cities};
        var cityIDS = [];
        for(var i=0;i<cities.length;i++)cityIDS.push(cities[i].id);
        $.getScript("${ctxPath}/assets/city-picker/weui-city-picker.js",function(a,b){
            var [省,dict市,市,区]=[$.rawCitiesData,{},[],[]];
            var 下级 = d => { for(var i=0,l=d.length,s=[];l&&i<l;i++)s=s.concat(d[i].sub);return s};
            for(var i=0;i<省.length;i++){
                市=市.concat(省[i].sub);
                区=区.concat(下级(省[i].sub));//第三级区单独作为一个[]
                for(j=0;j<省[i].sub.length;j++) dict市[省[i].sub[j].code]=省[i].sub[j];
            }
            window.省=省;//debug
            window.市=市;
            window.区=区;
            window.dict市=dict市;
        });

        // 添加
        $('#btnAdd').click(function(){
            showEditModel({});
        });

        // 搜索按钮点击事件
        $('#btnSearch').click(function () {
            $('#edtSearch').removeClass('layui-form-danger');
            var keyword = $.trim($('#edtSearch').val());
            var $tds = $('#areaTable').next('.treeTable').find('.layui-table-body tbody tr td');
            $tds.css('background-color', 'transparent');
            if (!keyword) {
                layer.msg("请输入关键字", {icon: 5, anim: 6});
                $('#edtSearch').addClass('layui-form-danger');
                $('#edtSearch').focus();
                return;
            }
            var searchCount = 0;
            $tds.each(function() {
                if ($(this).text().indexOf(keyword) >= 0) {
                    $(this).css('background-color', '#FAE6A0');
                    if (searchCount == 0) {
                        $('body,html').stop(true);
                        $('body,html').animate({scrollTop: $(this).offset().top - 150}, 500);
                    }
                    searchCount++;
                }
            });
            if (searchCount == 0) {
                layer.msg("没有匹配结果", {icon: 5, anim: 6});
            } else {
                treetable.expandAll('#areaTable');
            }
        });

        // 工具条点击事件
        table.on('tool(areaTable)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'edit') { // 修改
                showEditModel(data);
            } else if (layEvent === 'del') { // 删除
                doDel(data);
            }
        });

        form.on("select(id)",function(data){
            $("#name").val($("#id [value='"+data.value+"']").text());
        });
        table.on('tool(areaTable)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'edit') { // 修改
                showEditModel(data);
            } else if (layEvent === 'del') { // 删除
                doDel(data);
            }
        });
        function selectName(type){
            var options=["<option value='' >请选择"+(type==2?"城市":"地区")+"</option>"];
            if(type==2){
               $(市).each(function(k,v){
                    options.push("<option value="+v.code+">"+v.name+"</option>");
               });
               $("#id").html(options.join(""));
               form.render('select');
            }else if(type==3){
                selectType3();
            }
        }
        function selectType3(){
            var parentId = $("#parentId").val();
            var options=[];
            if(parentId&&parentId!=-1){
                $(dict市[parentId].sub).each(function(k,v){
                    options.push("<option value="+v.code+">"+v.name+"</option>");
                });
            }
            $("#id").html(options.join(""));
            form.render('select');
        }
        // 显示表单弹窗
        function showEditModel(mArea) {
            admin.open({
                type: 1,
                title: (mArea.id ? '修改' : '添加') + '区域',
                content: $('#modelArea').html(),
                success: function (layero, dIndex) {
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    // 回显数据
                    form.val('modelAreaForm', mArea);
                    //区域类型选择事件
                    function radio(type){
                        var types="";
                        if(type==2){
                            $("#city").hide();
                            types="城市";
                            $("#parentId").val("-1");
                        }else if(type==3){
                            $("#city").show();
                            types="地区";
                            $("#parentId").val(mArea.parentId);
                        }
                        selectName(type);
                        $("#area label").html(types);
                        //$("#area input").attr("placeholder", "请输入"+types+"名");
                    }
                    console.log(mArea);
                    form.on('radio(type)', function (data) {
                        radio(data.value);
                    });
                    form.on('select(parentId)', function (data) {
                        selectType3();
                    });

                    radio(mArea.id&&mArea.type||2);
                    form.val('modelAreaForm', mArea);
                    // 表单提交事件
                    form.on('submit(modelAreaSubmit)', function (data) {
                        layer.load(2);
                        $.post("addOrEdit", data.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.close(dIndex);
                                layer.msg(res.msg, {icon: 1});
                                // renderTable();
                                location.reload();
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'json');
                        return false;
                    });

                }
            });
        }

        // 删除
        function doDel(data) {
            top.layer.confirm('确定要删除“' + data.name + '”吗？', {
                skin: 'layui-layer-admin'
            }, function (i) {
                top.layer.close(i);
                layer.load(2);
                $.post('delete', {
                    id: data.id
                }, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        renderTable();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'json');
            });
        }

    });
</script>

</body>
</html>